package com.jiangruan.javaproject.request.service;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.entity.Result;
import com.jiangruan.javaproject.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:liufukai
 * @email:1324963242@qq.com
 * @desc:该类用于实现通过rpc调用比特币客户端的getbestblockhash功能
 * @datatime:2021/12/1511:33
 */
public class GetBestBlockHashService {
    public  String getBestBlockHash(){
        //准备rpc请求的用户的身份信息
        String auth=Constants.BITCOIN_RPC_USER+":"+Constants.BITCOIN_RPC_PWD;
        //java中实现base64编码
        Base64.Encoder encoder=Base64.getEncoder();
        String authBase64 = encoder.encodeToString(auth.getBytes());
        //准备请求头信息
        Map<String,String> header=new HashMap<>();
        header.put("Content-Type","application/json");
        header.put("Authorization", "Basic " +authBase64);

        //准备要发送的rpc数据
        Map<String,Object> body=new HashMap<>();
        body.put("id",1001);
        body.put("method","getbestblockhash");
        body.put("params",null);
        body.put("json_rpc","2.0");
        //将map转换成byte[]
        byte[] bodyBytes = JSONObject.toJSONBytes(body);
        //格式：{"id"，"1001","result":xxx,"error":null}
        String result= HttpUtils.post(Constants.BITCOIN_RPC_URL,header,bodyBytes);
        //反序列化
        Result result1 = JSONObject.parseObject(result, Result.class);
        System.out.println(result1.result);
        return result1.result;
    }
}
